package com.example.demo.service.impl;

import com.example.demo.entity.Order;
import com.example.demo.entity.Product;
import com.example.demo.entity.User;
import com.example.demo.service.ProductService;
import com.example.demo.service.UserBenefitService;
import com.example.demo.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 用户权益服务实现
 */
@Service
public class UserBenefitServiceImpl implements UserBenefitService {
    
    @Resource
    private UserService userService;
    
    @Resource
    private ProductService productService;
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUserBenefitsFromOrder(Order order) {
        try {
            // 获取用户信息
            Long userId = order.getUserId().longValue();


            User user = userService.getById(userId);
            if (user == null) {
                System.err.println("用户不存在: " + userId);
                return false;
            }
            
            // 从订单备注中解析商品信息
            String remark = order.getRemark();
            Product product = null;
            
            if (remark != null && remark.contains("基础聊天套餐")) {
                product = productService.getById("prod_001");
            } else if (remark != null && remark.contains("高级聊天套餐")) {
                product = productService.getById("prod_002");
            } else if (remark != null && remark.contains("VIP会员")) {
                product = productService.getById("prod_004");
            } else {
                // 默认使用基础套餐
                product = productService.getById("prod_001");
            }
            
            if (product != null) {
                // 记录更新前的权益信息
                Integer oldTokens = user.getTotalTokens();
                Integer oldValidityDays = user.getTotalValidityDays();
                
                updateUserBenefits(user, product);
                boolean updateResult = userService.updateById(user);
                
                if (updateResult) {
                    System.out.println("用户权益更新成功: 用户ID=" + user.getId() + 
                        ", Token数: " + oldTokens + " -> " + user.getTotalTokens() + 
                        ", 有效期: " + oldValidityDays + " -> " + user.getTotalValidityDays());
                    return true;
                } else {
                    System.err.println("用户权益更新失败: 数据库更新操作返回false");
                    return false;
                }
            } else {
                System.err.println("商品信息不存在，无法更新用户权益");
                return false;
            }
        } catch (Exception e) {
            System.err.println("从订单更新用户权益失败: " + e.getMessage());
            e.printStackTrace();
            throw e; // 重新抛出异常，触发事务回滚
        }
    }
    
    @Override
    public void updateUserBenefits(User user, Product product) {
        LocalDateTime now = LocalDateTime.now();
        
        // 更新token数量
        if (product.getToken() != null) {
            if (product.getToken() == -1) {
                // 无限制token
                user.setTotalTokens(-1);
            } else {
                // 累加token
                if (user.getTotalTokens() == null || user.getTotalTokens() == -1) {
                    user.setTotalTokens(product.getToken());
                } else {
                    user.setTotalTokens(user.getTotalTokens() + product.getToken());
                }
            }
        }
        
        // 更新有效期
        if (product.getValidityDays() != null) {
            if (product.getValidityDays() == -1) {
                // 永久有效
                user.setTotalValidityDays(-1);
                user.setExpiresAt(null);
            } else {
                // 计算新的过期时间
                LocalDateTime newExpiresAt;
                if (user.getExpiresAt() == null || user.getExpiresAt().isBefore(now)) {
                    // 如果当前没有权益或已过期，从当前时间开始计算
                    newExpiresAt = now.plusDays(product.getValidityDays());
                } else {
                    // 如果当前权益未过期，在现有基础上延长
                    newExpiresAt = user.getExpiresAt().plusDays(product.getValidityDays());
                }
                user.setExpiresAt(newExpiresAt);
                
                // 更新总有效天数
                if (user.getTotalValidityDays() == null || user.getTotalValidityDays() == -1) {
                    user.setTotalValidityDays(product.getValidityDays());
                } else {
                    user.setTotalValidityDays(user.getTotalValidityDays() + product.getValidityDays());
                }
            }
        }
        
        // 更新权益最后更新时间
        user.setLastBenefitUpdate(now);
    }
    
    @Override
    public User getUserBenefits(Long userId) {
        return userService.getById(userId);
    }
}
